package com.minshenglife.zanzan.web.power;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.minshenglife.zanzan.entity.Dept;
import com.minshenglife.zanzan.entity.power.ManagerEmp;
import com.minshenglife.zanzan.entity.power.WorkConDown;
import com.minshenglife.zanzan.service.power.DownLoadExcelService;
import com.minshenglife.zanzan.service.power.ManagerEmpService;

/**
 * 日志统计 导出Excel表格
 * 
 * @author wangpeng
 * 
 */
@Controller
@RequestMapping("/ExportWordCon")
public class ExportWordConController {

	Logger log = LoggerFactory.getLogger(ExportWordConController.class);

	@Resource
	DownLoadExcelService downLoadExcelService;

	@Resource
	ManagerEmpService managerEmpService;

	/**
	 * 导出excel文档
	 * 
	 * @param startDate
	 * 开始时间
	 * @param endDate
	 * 结束时间
	 * @param dept
	 * 选择部门
	 * @param request
	 * @param response
	 * @param modeMap
	 * @return
	 */
	@RequestMapping(value = "/downLoadExcel.power", method = RequestMethod.POST)
	public String downLoadExcel(String startDate, String endDate, String dept, ModelMap modeMap, HttpSession session, HttpServletRequest request, HttpServletResponse response) throws ParseException {
		log.info("start   downLoadExcel ，dept---"+dept);
		try {
			Map<String, Object> map = new HashMap<String, Object>();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date firstDate = null;
			Date secondDate = null;

			session = request.getSession();
			ManagerEmp managerEmp = (ManagerEmp) session.getAttribute("managerEmp");

			if (!"".equals(startDate)) {
				firstDate = sdf.parse(startDate);
				map.put("firstDate", firstDate);
			}
			if (!"".equals(endDate)) {
				secondDate = sdf.parse(endDate);
				map.put("secondDate", secondDate);
			}

			if (managerEmp == null) {
				// modeMap.addAttribute("error", "用户状态已失效！");
//				return "/jsp/power/managlogin";
				return "/manage/login";
			}

			String dept_name = "";
			if (dept != null && !dept.equals("")) {
				if (dept.equals("1") && dept == "1") {
					log.info("dept.equals(\"1\") && dept == \"1\"");
				} else {
					dept_name = managerEmpService.finddet_name(dept);
				}
			} else {
				if (managerEmp.getDept_id().equals("1")) {
					dept_name = null;
				} else {
					dept_name = managerEmpService.finddet_name(managerEmp.getDept_id());
				}

			}
			map.put("dept_name", dept_name);
			List<List<WorkConDown>> results = downLoadExcelService.getWorkCon(firstDate, secondDate, dept_name);
			if (null != results && results.size() > 0) {
				response.setContentType("application/vnd.ms-excel");
				try {
					response.setHeader("Content-Disposition", "attachment;" + "filename=" + new String((dept_name + "微家工作日志填写统计表.xls").getBytes("GBK"), "ISO-8859-1"));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				try {
					OutputStream out = response.getOutputStream();
					//System.out.println(results.size());
					downLoadExcelService.getWorkExcel(map, results, out);
					out.flush();
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
				log.info("end   downLoadExcel() ");
				return "/jsp/power/downloadExcel";
			} else {
				modeMap.addAttribute("error", "没有数据");
//				return "/jsp/power/managlogin";
				return "/manage/login";
			}
		} catch (Exception e) {
			e.printStackTrace();
			return "/jsp/manage/error";
		} finally {
			log.info("end   downLoadExcel() ");
		}
	}

	/**
	 * 更新部门 (已不用)
	 * 
	 * @param map
	 * @param request
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value = "/getDept_name.power", method = RequestMethod.POST)
	public String getDept_name(ModelMap map, HttpServletRequest request) {
		HttpSession session1 = request.getSession();
		ManagerEmp managerEmp = (ManagerEmp) session1.getAttribute("managerEmp");
		if (managerEmp == null) {
			map.addAttribute("error", "用户状态已失效！");
//			return "/jsp/power/managlogin";
			return "/manage/login";
		}
		if (managerEmp.getGrade().equals("1")) {
			map.put("dept_name", "");
		} else {
			String dept_name = managerEmpService.finddet_name(managerEmp.getDept_id());
			map.put("dept_name", dept_name);
			map.addAttribute("dept_name", dept_name);
		}
		String result = downLoadExcelService.getDept_name(map);
		log.info(result);
		return result;
	}

	/**
	 * 跳转到excel文档下载
	 * 
	 * @param map
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "/skipExcelWork.power", method = RequestMethod.GET)
	public String skipExcelWork(ModelMap map, HttpServletRequest request) {
		HttpSession session1 = request.getSession();
		ManagerEmp managerEmp = (ManagerEmp) session1.getAttribute("managerEmp");
		if (managerEmp != null) {
			if (managerEmp.getGrade().equals("1")) {
				map.put("dept_name", "");
			} else {
				String dept_name = managerEmpService.finddet_name(managerEmp.getDept_id());
				map.put("dept_name", dept_name);
				map.addAttribute("dept_name", dept_name);
			}
			List<Dept> deptList = downLoadExcelService.getDeptList(map);
			StringBuffer treeTop = new StringBuffer();
			StringBuffer tree = new StringBuffer();
			int minNodeValue = Integer.MAX_VALUE;
			Dept topTreeDept = null;
			for (Dept dept : deptList) {
				tree.append("mytree.add("+dept.getDept_id()+","+dept.getParentNodeId() +",'"+dept.getAbbr_name()+"','');");
				if(minNodeValue > Integer.valueOf(dept.getDept_id())){
					minNodeValue = Integer.valueOf(dept.getDept_id());
					topTreeDept = dept;
				}
			}
			treeTop.append("mytree.add("+(topTreeDept.getParentNodeId() == null ? 0 : topTreeDept.getParentNodeId())+",-1,'民生 保险','');");
			treeTop.append("mytree.add("+minNodeValue+","+(topTreeDept.getParentNodeId() == null ? 0:topTreeDept.getParentNodeId())+",'"+topTreeDept.getAbbr_name()+"','');");
			treeTop.append(tree);
			map.addAttribute("treeMap", treeTop.toString());
			return "/jsp/power/downloadExcel";
		} else {
			map.addAttribute("error", "用户状态已失效！");
//			return "/jsp/power/managlogin";
			return "/manage/login";
		}
	}

	public static void main(String[] args) throws ParseException {
		String ss = "2015-06-18 14:24:39";
		String ss1 = "2015-06-23 14:24:39";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Date firstDate = null;
		firstDate = sdf.parse(ss);
		Date secondDate = null;
		secondDate = sdf.parse(ss1);
		Calendar cal = Calendar.getInstance();
		cal.setTime(firstDate);
		int startDate = cal.get(Calendar.DAY_OF_MONTH);
		cal.setTime(secondDate);
		int endDate = cal.get(Calendar.DAY_OF_MONTH);
		for (int i = startDate; i <= endDate; i++) {
			cal.setTime(firstDate);
			cal.add(Calendar.DATE, 1);
			firstDate = cal.getTime();
			System.out.println(firstDate);
		}
	}
}
